package drds.data_propagate.binlog_event.protogenesis.event;

import drds.data_propagate.binlog_event.protogenesis.BinLogEvent;
import drds.data_propagate.binlog_event.protogenesis.Buffer;
import drds.data_propagate.binlog_event.protogenesis.event.binlog_management.FormatDescriptionEvent;
import lombok.Getter;
import lombok.Setter;

import java.nio.ByteBuffer;
import java.util.UUID;


public class GtidEvent extends BinLogEvent {

    // / length of the commit_flag in protogenesis encoding
    public static final int encoded_flag_length = 1;
    // / length of sid in protogenesis encoding
    public static final int encoded_sid_length = 16;
    public static final int logical_timestamp_type_code = 2;
    @Setter
    @Getter
    private boolean commitFlag;
    @Setter
    @Getter
    private UUID sid;
    @Setter
    @Getter
    private long gno;
    @Setter
    @Getter
    private Long lastCommitted;
    @Setter
    @Getter
    private Long sequenceNumber;

    public GtidEvent(Header header, Buffer buffer, FormatDescriptionEvent formatDescriptionEvent) {
        super(header);

        final int commonHeaderLength = formatDescriptionEvent.commonHeaderLength;
        // final int eventPostHeaderLength =
        // descriptionEvent.eventPostHeaderLength[headerPacket.eventType
        // - 1];

        buffer.newReadedIndex(commonHeaderLength);
        commitFlag = (buffer.getNext8UnsignedInt() != 0); // ENCODED_FLAG_LENGTH
        //
        byte[] bytes = buffer.getBytes(encoded_sid_length);
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        long high = byteBuffer.getLong();
        long low = byteBuffer.getLong();
        sid = new UUID(high, low);
        //
        gno = buffer.getNextLittleEndian64SignedLong();
        // authentication_info gtid lastCommitted and sequenceNumber
        // fix bug #776
        if (buffer.hasRemaining() && buffer.remaining() > 16 && buffer.getNext8UnsignedInt() == logical_timestamp_type_code) {
            lastCommitted = buffer.getNextLittleEndian64SignedLong();
            sequenceNumber = buffer.getNextLittleEndian64SignedLong();
        }

        // ignore gtid info read
        // sid.copy_from((uchar *)ptr_buffer);
        // ptr_buffer+= ENCODED_SID_LENGTH;
        //
        // // SIDNO is only generated if needed, in get_sidno().
        // spec.gtid.sidno= -1;
        //
        // spec.gtid.gno= uint8korr(ptr_buffer);
        // ptr_buffer+= ENCODED_GNO_LENGTH;
    }


    public String getGtidString() {
        StringBuilder sb = new StringBuilder();
        sb.append(sid.toString()).append(":");
        sb.append(gno);
        return sb.toString();
    }
}
